package com.autonavi.yunda.yunji.service;

import com.alibaba.buc.sso.client.util.SimpleUserUtil;
import com.alibaba.buc.sso.client.vo.BucSSOUser;
import com.autonavi.yunda.yunji.common.exception.AmapPreconditions;
import com.autonavi.yunda.yunji.core.enums.OperationRecordType;
import com.autonavi.yunda.yunji.core.model.condition.OperationQueryCondition;
import com.autonavi.yunda.yunji.core.model.dto.OperationRecordDTO;
import com.autonavi.yunda.yunji.core.model.mappers.OperationRecordMapper;
import com.autonavi.yunda.yunji.core.vo.response.OperationPageVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.autonavi.yunda.yunji.common.constant.CommonConstant.MDC_TRACE_ID;

/**
 * @author sunzhenbang
 */
@Service
@Slf4j
public class OperationRecordService {
    @Resource
    OperationRecordMapper operationRecordMapper;
    @Resource
    BucUserService bucUserService;
    @Resource
    HttpServletRequest request;
    @Resource
    FactoryUserService factoryUserService;

    public OperationPageVO listPage(OperationQueryCondition condition) {
        Page<OperationRecordDTO> page = new Page<>(condition.getPageNo(), condition.getPageSize());
        QueryWrapper<OperationRecordDTO> wrapper = condition.getFunctionWrapper(condition);
        Long bdId = factoryUserService.getCurrentUserBdId();
        if (bdId != null) {
            wrapper.eq("bd_id", bdId);
        }
        operationRecordMapper.selectPage(page, wrapper);
        return new OperationPageVO(page.getRecords(), page.getTotal());
    }

    public void add(OperationRecordType type, String relatedId) {
        try {
            BucSSOUser bucSSOUser = SimpleUserUtil.getBucSSOUser(request);
            AmapPreconditions.checkArgumentForUser(bucSSOUser != null && StringUtils.isNotBlank(bucSSOUser.getEmpId()), "用户不存在");
            OperationRecordDTO operationRecordDTO = OperationRecordDTO.builder()
                    .operatorId(bucUserService.getCurEmployeeIdOrNull())
                    .bdId(factoryUserService.getCurrentUserBdId())
                    .operatorName(bucSSOUser.getLastName())
                    .type(type.getType())
                    .subType(type.getOperation())
                    .relatedId(relatedId)
                    .traceId(MDC.get(MDC_TRACE_ID)).build();
            operationRecordMapper.insert(operationRecordDTO);
        } catch (Exception e) {
            log.error("operation record error", e);
        }
    }

}
